package com.config;


import com.common.Constants;
import com.module.user.pojo.UserSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 跨域访问 --- 拦截器
 */
public class AppHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession httpSession = httpServletRequest.getSession();
        UserSession userSession= (UserSession)httpSession.getAttribute(Constants.SESSION_USER_KEY);
        String token = httpServletRequest.getHeader("Authorization");
        String url = httpServletRequest.getRequestURI();
        if(!url.contains("login")&&userSession!=null) {
            String sessionId =userSession.getToken();
            if (!sessionId.equals(token)) {
                httpServletResponse.setContentType("text/json;charset=utf-8");
                httpServletResponse.setHeader("Cache-Control", "no-cache");
                httpServletResponse.setHeader("Expires", "0");
                httpServletResponse.setHeader("Pragma", "No-cache");
                try {
                    PrintWriter out = httpServletResponse.getWriter();
                    out.print("{\"isSuccess\":\"false\",\"info\":\"Token失效\"}");
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
